package com.gsafety.libraryktx.expand

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.gsafety.library.Net.RetrofitExt.common.SCallBack
import com.gsafety.libraryktx.base.RespBaseBean
import com.gsafety.libraryktx.net.callback.CommonCallBack
import kotlinx.coroutines.*
import retrofit2.Call


/**
 * 使用协程的方式来网路请求，会根据生命周期自动取消
 */
inline fun <reified T> ViewModel.enqueue(
    call: Call<RespBaseBean<T>>,
    noinline onSuccess: ((result: T?) -> Unit),
    noinline onFinally: (() -> Unit)? = null,
    noinline onFail: ((msg: String?) -> Unit)? = null
) {
    viewModelScope.launch {
        call.enqueue(onSuccess, onFinally, onFail)
    }
}


inline fun <reified T> ViewModel.commonEq(
    call: Call<T>,
    noinline onSuccess: ((result: T) -> Unit),
    noinline onFinally: (() -> Unit)? = null,
    noinline onFail: ((msg: String?) -> Unit)? = null
) {
    viewModelScope.launch {
        call.enqueue(object : SCallBack<T>() {
            override fun onSuccess(result: T) {
                onSuccess(result)
            }

            override fun onFail(call: Call<T>, t: Throwable) {
                super.onFail(call, t)
            }
        })
    }
}